package com.cicc.springboot.utile;

import java.util.concurrent.atomic.AtomicInteger;

public class OrderNumberGenerator {
    private static final AtomicInteger orderCount = new AtomicInteger(0);
    private static long lastTime = 0;

    public static String generateOrderNumber() {
        long currentTime = System.currentTimeMillis();

        // 如果当前时间和上次生成的时间相同，增加计数
        if (currentTime == lastTime) {
            if (orderCount.get() >= 999) {
                // 超过999，等待下一毫秒
                while (currentTime == lastTime) {
                    currentTime = System.currentTimeMillis();
                }
                orderCount.set(0); // 重置计数器
            }
        } else {
            lastTime = currentTime;
            orderCount.set(0); // 重置计数器
        }

        // 获取顺序数字，三位，不足前补零
        String orderSeq = String.format("%03d", orderCount.incrementAndGet());

        // 拼接时间戳和顺序数字
        String orderNumber = String.valueOf(currentTime) + orderSeq;

        // 确保订单编号长度为16位，若不足则填充0
        return String.format("%016d", Long.parseLong(orderNumber));
    }
}
